package app 
{
	import app.modules.ModuleChoseFurniture;
	import app.textures.TextureInfoGroupe;
	import com.bit101.components.HBox;
	import com.bit101.components.PushButton;
	import com.bit101.components.Text;
	import com.bit101.components.VBox;
	import com.bit101.components.WheelMenu;
	import events.AppModelEvents;
	import events.FurniturePalleteEvent;
	import events.ModuleBottomEvent;
	import events.Scene3DEvent;
	import fl.controls.Label;
	import fl.controls.TileList;
	import fl.video.FLVPlayback;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.Graphics;
	import flash.display.MovieClip;
	import flash.display.Shape;
	import flash.display.SimpleButton;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.external.ExternalInterface;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.geom.Vector3D;
	import flash.net.navigateToURL;
	import flash.net.URLRequest;
	import flash.ui.Keyboard;
	import furnitures.FurnitureFactory;
	import furnitures.FurnitureModel;
	import gui.buttons.BaseButton;
	import gui.buttons.LabelButton;
	import gui.buttons.RadioButton;
	import gui.factory.StyleFactory;
	import gui.PositionInfo;
	import messages.MessageLoading;
	import utils.Logger;
	/**
	 * ...
	 * @author Dmitriy Gaiduk
	 */
	public class AppView extends Sprite
	{
		private var _model:AppModel;
		private var _topBar:Sprite;
		
		private var _bottomBar:Sprite;
		private var _rightBar:Sprite;
		
		// buttons 
		private var _roomSizeBtn:RadioButton;
		private var _bottomFurnitureBtn:RadioButton;
		private var _topFurnitureBtn:RadioButton;
		private var _techFurnitureBtn:RadioButton;
		
		// service
		private var _btnFavorite:BaseButton;
		private var _btnPrint:BaseButton;
		private var _btnCalculate:BaseButton;
		private var _btnTutor:BaseButton;
		private var _btnGallery:BaseButton;
		
		private var _currentRightModule:DisplayObject;
		private var _currentBottomModule:DisplayObject;
		private var _moduleHolder:Sprite;
		//private var _scene3D:Scene3D;
		private var _scene3D:Scene3DAlter;
		
		private var _btnAddFurniture:LabelButton;
		private var _btnRemoveFurniture:LabelButton;
		
		private var _btnFacadeChoose:RadioButton;
		private var _btnTabletopChoose:RadioButton;
		
		private var _radBtnPerspectiveNormal:RadioButton;
		private var _radBtnPerspectiveUp:RadioButton;
		private var _radBtnPerspectiveLeft:RadioButton;
		private var _radBtnPerspectiveRight:RadioButton;
		
		
		private const PERSPECTIVE_GROUP:String = "PERSPECTIVE_GROUP";
		private const MAIN_FOLDER_GROUP:String = "MAIN_FOLDER_GROUP";
		
		private var _activePanelHolder:Sprite;
		private const ZOOM_IN:int = 0;
		private const ZOOM_OUT:int = 1;
		private const ZOOM_SPEED:Number = 0.25;
		
		private var _zoomState:int;
		private var _zoomInBtn:SimpleButton;
		private var _zoomOutBtn:SimpleButton;
		private var _zoomNoZoom:SimpleButton;
		
		private var _timer:int;
		private const PAUSE_TIME:int = 2;
		
		
		
		private static const PROCESS_ADD_FURNITURE:String = "PROCESS_ADD_FURNITURE";
		private static const PROCESS_UPDATE_TABLETOP:String = "PROCESS_UPDATE_TABLETOP";
		private static const PROCESS_UPDATE_FACADE:String = "PROCESS_UPDATE_FACADE";
		private static const PROCESS_UPDATE_CORPUS:String = "PROCESS_UPDATE_CORPUS";
		private static const PROCESS_NONE:String = "PROCESS_NONE";
		
		private var _processType:String = PROCESS_NONE;
		private var _moduleBottom:ModuleBottom;
		private var _perspectiveMessage:MovieClip;
		
		private const SCENE3D_WIDTH:Number = 1050;
		private const SCENE3D_HEIGHT:Number = 600;
		
		private var _testShape:Sprite;
		private const NO_ZOOM_SCALE:Number = 0.30;
		
		private var _messageLoading:MessageLoading;
		private var _videoModule:Sprite;
		private var _sceneWidth:Number;
		private var _sceneHeight:Number;
		
		
		public function AppView(model:AppModel) 
		{
			_model = model;
			addEventListener(Event.ADDED_TO_STAGE, handleAddedToStage);
		}
		
		
		private function handleAddedToStage(e:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, handleAddedToStage);
			trace("App view start!!");
			
			initApp();
		}
		
		private function initApp():void 
		{
			_model.paletteProvider.setupPalette(_model.techTextureGroupe, 
												_model.techTextureGroupe.textures[0]);
			_zoomState = -1;
			_timer = 0;
			
			/*if ((_model.facadeTextures != null) &&
			    _model.facadeTextures.length > 0)
				{
					if ((_model.facadeTextures[0].textures != null) &&
					    (_model.facadeTextures[0].textures.length > 0))
						{
							_model.currentFacadeTexture = _model.facadeTextures[0].textures[0];
						}
				}
			if ((_model.tabletopTextures != null) &&
			    _model.tabletopTextures.length > 0)
				{
					if ((_model.tabletopTextures[0].textures != null) &&
					    (_model.tabletopTextures[0].textures.length > 0))
						{
							_model.currentTabletopTexture = _model.tabletopTextures[0].textures[0];
						}
				}*/
			
			//var rigthBarWidth:Number = StyleFactory.RIGHT_BAR_WIDTH;
			//var leftBarsWidth:Number = AppSettings.APP_WIDTH - rigthBarWidth;
			
			
			createCentrBar();
			createTopBar();
			createBottomBar();
			createRightBar();
			
			//_model.addEventListener(AppModelEvents.FACADE_TEXTURE_CHANGE, handleFacadeTextureChange);
			//_model.addEventListener(AppModelEvents.TABLETOP_TEXTURE_CHANGE, handleTabletopTextureChange);
			_model.addEventListener(AppModelEvents.ROOM_SIZE_CHANGE, handleRoomSizeChange);
			_model.paletteProvider.addEventListener(FurniturePalleteEvent.FACADE_PALETTE_CHANGED, 
				handleFacadePaletteChanged);
			_model.paletteProvider.addEventListener(FurniturePalleteEvent.TABLETOP_PALETTE_CHANGED, 
										handleTabletoppaletteChanged);
			
			_bottomFurnitureBtn.selected = true;
			//_model.addEventListener(AppModelEvents.FURNITURE_TYPE_CHANGE, handleFurnTypeChange);
			stage.addEventListener(Event.ENTER_FRAME, handleEnterFrameMainStep);
			stage.addEventListener(MouseEvent.MOUSE_UP, handleMouseUp);
			
			_testShape = new Sprite();
			addChild(_testShape);
			_testShape.y = StyleFactory.HEADER_HEIGHT + 12;
			_testShape.x = 12;
		}
		
		private function handleTabletoppaletteChanged(e:FurniturePalleteEvent):void 
		{
			if (_model.paletteProvider.tabletopPalette != null)
			{
				//_scene3D.setTabletopPalette(_model.paletteProvider.tabletopPalette);
			}
		}
		
		
		private function handleFacadePaletteChanged(e:FurniturePalleteEvent):void 
		{
			if (_model.paletteProvider.facadePalette != null)
			{
				//_scene3D.setFacadePalette(_model.paletteProvider.facadePalette);
			}
		}
		
		private function log(msg:String):void
		{
			Logger.log(this, msg);
		}
		
		private function handleMouseUp(e:MouseEvent):void 
		{
			_zoomState = -1;
			_timer = -1;
		}
		
		private function handleEnterFrameMainStep(e:Event):void 
		{
			_timer--;
			if (_timer <= 0)
			{
				_timer = PAUSE_TIME;
			}else
			{
				return;
			}
			switch(_zoomState)
			{
				case ZOOM_IN:
						_scene3D.zoom += ZOOM_SPEED;
					break;
				case ZOOM_OUT:
						_scene3D.zoom -= ZOOM_SPEED;
					break;
			}
			
		}
		
		private function createCentrBar():void 
		{
			var container:DisplayObjectContainer = new Sprite();
			addChild(container);
			container.y = StyleFactory.HEADER_HEIGHT;
			//container.x = 220;
			
			var centrBg:DisplayObject = new SceneBackground();
			container.addChild(centrBg);
			
			var headerH:Number = StyleFactory.HEADER_HEIGHT;
			
			//var scene3dContainer:Sprite = new Sprite();
			//scene3dContainer.y = StyleFactory.HEADER_HEIGHT;
			//stage.addChild(scene3dContainer);
			//container.addChild(scene3dContainer);
			
			var sceneMask:DisplayObject = new SceneMask();
			sceneMask.x = 12;
			sceneMask.y = 12;
			//container.addChild(sceneMask);
			
			
			
			// add scene3d
			_sceneWidth = 1027;
			_sceneHeight = 577;
			_scene3D = new Scene3DAlter(_sceneWidth, _sceneHeight, _model.paletteProvider);
			//_scene3D = new Scene3DAlter(500, 500);
			//_scene3D = new Scene3D(NO_ZOOM_SCALE, 500 * AppSettings.SCALE_FACTOR);
			_scene3D.addEventListener(Scene3DEvent.SCENE_UPDATED, handleSceneUpdated);
			_scene3D.roomWidth = _model.roomWidth;
			_scene3D.roomHeight = _model.roomHeight;
			_scene3D.roomLenght = _model.roomLength;
			// corner
			_scene3D.x = 12;
			_scene3D.y = 12;
			container.addChild(_scene3D);
			
			//_scene3D.mask = sceneMask;
			
			//var HorizSpacing:Number = 5;
			
			var zoomHolder:Sprite = new Sprite();
			_zoomInBtn = new ZoomInBtn();
			//StyleFactory.setButtonStyle(_zoomInBtn, StyleFactory.BTN_ZOOM_IN);
			zoomHolder.addChild(_zoomInBtn);
			_zoomInBtn.addEventListener(MouseEvent.MOUSE_DOWN, handleZoomDown);
			
			_zoomNoZoom = new NoZoomBtn();
			//StyleFactory.setButtonStyle(_zoomNoZoom, StyleFactory.BTN_ZOOM_NO_ZOOM);
			_zoomNoZoom.addEventListener(MouseEvent.CLICK, handleNoZoomClick);
			zoomHolder.addChild(_zoomNoZoom);
			_zoomNoZoom.x = 28;
			_zoomNoZoom.y = 3;
			
			_zoomOutBtn = new ZoomOutBtn();
			//StyleFactory.setButtonStyle(_zoomOutBtn, StyleFactory.BTN_ZOOM_OUT);
			_zoomOutBtn.addEventListener(MouseEvent.MOUSE_DOWN, handleZoomDown);
			zoomHolder.addChild(_zoomOutBtn);
			_zoomOutBtn.x = 50;
			
			zoomHolder.x =957;
			zoomHolder.y = 612 - 50;
			container.addChild(zoomHolder);
			
			// perspective message
			_perspectiveMessage = new PerspectiveMessagesMovie();
			container.addChild(_perspectiveMessage);
			_perspectiveMessage.x = 937;
			_perspectiveMessage.y = 596 - 50;
			_perspectiveMessage.gotoAndStop(1);
			
			_scene3D.addEventListener(Scene3DEvent.SCENE_UPDATED, handleSceneUpdated);
			_scene3D.setPerspective(Scene3DAlter.PERSPECTIVE_CENTR);
		}
		
		
		private function handleNoZoomClick(e:MouseEvent):void 
		{
			//_scene3D.scaleFactor = NO_ZOOM_SCALE;
			_scene3D.zoom = NO_ZOOM_SCALE;
			_scene3D.addEventListener(Scene3DEvent.SCENE_UPDATED, handleSceneUpdated);
		}
		
		private function handleZoomDown(e:MouseEvent):void 
		{
			_timer = -1;
			switch(e.currentTarget)
			{
				case _zoomInBtn:
						_zoomState = ZOOM_IN;
					break;
				case _zoomOutBtn:
						_zoomState = ZOOM_OUT;
					break;
			}
			
		}
		
		/*private function handleKeyUp(e:KeyboardEvent):void 
		{
			if (e.keyCode == Keyboard.UP)
			{
				_scene3D.scaleFactor += 0.1;
			}else if (e.keyCode == Keyboard.DOWN)
			{
				_scene3D.scaleFactor -= 0.1;
			}
		}*/
		
		private function handleRoomSizeChange(e:AppModelEvents):void 
		{
			_scene3D.setRoomSize(_model.roomWidth, _model.roomLength, _model.roomHeight);
		}
		
		/*private function handleTabletopTextureChange(e:AppModelEvents):void 
		{
			_scene3D.setTabletopTexture(_model.currentTabletopTexture);
		}
		
		private function handleFacadeTextureChange(e:AppModelEvents):void 
		{
			_scene3D.setFaceTexture(_model.currentFacadeTexture);
		}
		*/
		
	
		
		private function createRightBar():void 
		{
			_rightBar = new Sprite();
		
			addChild(_rightBar);
			_rightBar.x = AppSettings.APP_WIDTH - StyleFactory.RIGHT_BAR_WIDTH;
			_rightBar.y = 0;
			_activePanelHolder = new Sprite();
			_rightBar.addChild(_activePanelHolder);
			
			//drawBar(_rightBar.graphics, wBar, hBar, 0x3399CC);
			
			
			var leftPad:Number = 0;
			var topPad:Number = 0;
			
			
			//var btnChooseModuleBox:VBox = new VBox(_rightBar, leftPad, topPad);
				//btnChooseModuleBox.spacing = 1;
			
			var horizSpacing:Number = 2;
			var btnChooseModuleBox:Sprite = new Sprite();
			_rightBar.addChild(btnChooseModuleBox);
			btnChooseModuleBox.x = leftPad;
			btnChooseModuleBox.y = topPad;
			
			
			_roomSizeBtn = new RadioButton();
			_roomSizeBtn.groupName = MAIN_FOLDER_GROUP;
			//_roomSizeBtn.label = "Размер помещения";
			StyleFactory.setRadioButtonStyle(_roomSizeBtn, StyleFactory.STYLE_RB_ROOM_SIZE);
			_roomSizeBtn.addEventListener(Event.CHANGE, handleBtnModulChooser);
			btnChooseModuleBox.addChild(_roomSizeBtn);
			
			_bottomFurnitureBtn = new RadioButton();
			_bottomFurnitureBtn.groupName = MAIN_FOLDER_GROUP;
			_bottomFurnitureBtn.label = "Нижние шкафы";
			StyleFactory.setRadioButtonStyle(_bottomFurnitureBtn, StyleFactory.STYLE_RB_FURNITURE_BOTTOM);
			_bottomFurnitureBtn.addEventListener(Event.CHANGE, handleBtnModulChooser);
			_bottomFurnitureBtn.y = _roomSizeBtn.y + _roomSizeBtn.height + horizSpacing;
			btnChooseModuleBox.addChild(_bottomFurnitureBtn);
			
			_topFurnitureBtn = new RadioButton();
			_topFurnitureBtn.groupName = MAIN_FOLDER_GROUP;
			//_topFurnitureBtn.label = "Верхние шкафы";
			StyleFactory.setRadioButtonStyle(_topFurnitureBtn, StyleFactory.STYLE_RB_FURNITURE_TOP);
			_topFurnitureBtn.addEventListener(Event.CHANGE, handleBtnModulChooser);
			_topFurnitureBtn.y = _bottomFurnitureBtn.y + _bottomFurnitureBtn.height + horizSpacing;
			btnChooseModuleBox.addChild(_topFurnitureBtn);
			
			_techFurnitureBtn = new RadioButton();
			_techFurnitureBtn.groupName = MAIN_FOLDER_GROUP;
			//_topFurnitureBtn.label = "Техника";
			StyleFactory.setRadioButtonStyle(_techFurnitureBtn, StyleFactory.STYLE_RB_TECH);
			_techFurnitureBtn.addEventListener(Event.CHANGE, handleBtnModulChooser);
			_techFurnitureBtn.y = _topFurnitureBtn.y + _topFurnitureBtn.height + horizSpacing;
			btnChooseModuleBox.addChild(_techFurnitureBtn);
			
			
			/*log("_roomSizeBtn y: " + _roomSizeBtn.y + " " +_roomSizeBtn.height);
			log("_bottomFurnitureBtn y: " + _bottomFurnitureBtn.y + " " + _bottomFurnitureBtn.height);
			log("_topFurnitureBtn y: " + _topFurnitureBtn.y + " " +_topFurnitureBtn.height);
			log("_techFurnitureBtn y: " + _techFurnitureBtn.y + " " +_techFurnitureBtn.height);*/
			
			//150
			
			//var rectW:Number = 186;
			//var rectH:Number = 200;
			
			
			
			_moduleHolder = new Sprite();
			_rightBar.addChild(_moduleHolder);
			_moduleHolder.x = 0;
			_moduleHolder.y = btnChooseModuleBox.y + _techFurnitureBtn.y + _techFurnitureBtn.height;
			
			
			//perspective
			var perspectiveHolder:Sprite = new Sprite();
			var perspectBg:Sprite = new Perspective_Background();
			perspectiveHolder.addChild(perspectBg);
			_rightBar.addChild(perspectiveHolder);
			
			//var radBtnVBox:VBox = new VBox(perspectiveHolder, 0, 18);
			//var radBtnHBox:HBox = new HBox();
			
			_radBtnPerspectiveNormal = new RadioButton();
			
			
			_radBtnPerspectiveNormal.groupName = PERSPECTIVE_GROUP;
			_radBtnPerspectiveNormal.x = 0;
			_radBtnPerspectiveNormal.y = 15;
			//_radBtnPerspectiveNormal.label = "Перспектива";
			_radBtnPerspectiveNormal.selected = true;
			_radBtnPerspectiveNormal.buttonMode = true;
			_radBtnPerspectiveNormal.addEventListener(MouseEvent.CLICK, handlePerspectiveClick);
			StyleFactory.setRadioButtonStyle(_radBtnPerspectiveNormal, StyleFactory.STYLE_RB_PROJ_PERSPETCTIVE);
			perspectiveHolder.addChild(_radBtnPerspectiveNormal);
			
			_radBtnPerspectiveUp = new RadioButton();
			_radBtnPerspectiveUp.x = 115;
			_radBtnPerspectiveUp.y = 15;
			_radBtnPerspectiveUp.groupName = PERSPECTIVE_GROUP;
			//_radBtnPerspectiveUp.label = "Вид сверху";
			_radBtnPerspectiveUp.addEventListener(MouseEvent.CLICK, handlePerspectiveClick);
			StyleFactory.setRadioButtonStyle(_radBtnPerspectiveUp, StyleFactory.STYLE_RB_PROJ_UP);
			perspectiveHolder.addChild(_radBtnPerspectiveUp);
			
		
			_radBtnPerspectiveLeft = new RadioButton();
			_radBtnPerspectiveLeft.x = 0;
			_radBtnPerspectiveLeft.y = 80;
			_radBtnPerspectiveLeft.groupName = PERSPECTIVE_GROUP;
			//_radBtnPerspectiveLeft.label = "Вид слева";
			StyleFactory.setRadioButtonStyle(_radBtnPerspectiveLeft, StyleFactory.STYLE_RB_PROJ_LEFT);
			_radBtnPerspectiveLeft.addEventListener(MouseEvent.CLICK, handlePerspectiveClick);
			perspectiveHolder.addChild(_radBtnPerspectiveLeft);
			
			_radBtnPerspectiveRight = new RadioButton();
			_radBtnPerspectiveRight.x = 115;
			_radBtnPerspectiveRight.y = 80;
			_radBtnPerspectiveRight.groupName = PERSPECTIVE_GROUP;
			//_radBtnPerspectiveRight.label = "Вид справа";
			StyleFactory.setRadioButtonStyle(_radBtnPerspectiveRight, StyleFactory.STYLE_RB_PROJ_RIGHT);
			_radBtnPerspectiveRight.addEventListener(MouseEvent.CLICK, handlePerspectiveClick);
			perspectiveHolder.addChild(_radBtnPerspectiveRight);
			
			var perspectivePos:PositionInfo = new PositionInfo();
			perspectivePos.align = PositionInfo.ALIGN_BOTTOM;
			perspectivePos.rightPadding = 15;
			perspectivePos.bottomPadding = 15;
			perspectivePos.addAlign(PositionInfo.ALIGN_RIGHT);
			//perspectiveHolder.x = perspectivePos.getPosX(wBar, perspectiveHolder.width);
			//perspectiveHolder.y = perspectivePos.getPosY(hBar, perspectiveHolder.height);
			perspectiveHolder.x = perspectivePos.getPosX(StyleFactory.RIGHT_BAR_WIDTH, perspectiveHolder.width);
			perspectiveHolder.y = perspectivePos.getPosY(AppSettings.APP_HEIGHT, perspectiveHolder.height);
			
			
			// add furn
			var vBoxAddRemove:VBox = new VBox();
			vBoxAddRemove.spacing = 10;
			_btnAddFurniture = new LabelButton();
			StyleFactory.setButtonStyle(_btnAddFurniture, StyleFactory.STYLE_BUTTON_ADD);
			
			//_btnAddFurniture.label = "Добавить";
			//_btnAddFurniture.textField.x = 50;
			vBoxAddRemove.addChild(_btnAddFurniture);
			_btnAddFurniture.addEventListener(MouseEvent.CLICK, handleBtnAddFurnClick);
			
			// remove furn
			_btnRemoveFurniture = new LabelButton();
			StyleFactory.setButtonStyle(_btnRemoveFurniture, StyleFactory.STYLE_BUTTON_REMOVE);
			vBoxAddRemove.addChild(_btnRemoveFurniture);
			_btnRemoveFurniture.addEventListener(MouseEvent.CLICK, handleBtnRemoveFurnClick);
			
			vBoxAddRemove.y = perspectiveHolder.y - vBoxAddRemove.height - 15;
			vBoxAddRemove.x = StyleFactory.RIGHT_BAR_WIDTH - vBoxAddRemove.width - 25;
			_rightBar.addChild(vBoxAddRemove);
			
		}
		
		
		
		private function handlePerspectiveClick(e:MouseEvent):void 
		{
			/*
			rotation x: -2.363175630569458 y: 0.5235987901687622 z: 2.6450464725494385
				rotation degreee x: -135.39998987979695 y: 30.000000834826057 z: 151.54999949304877
				.rotationY = 30 * Math.PI / 180;;
				
				// left
				rotation x: -1.5952308177947998 y: 0 z: -3.135483980178833
				rotation degreee x: -91.39999320884485 y: 0 z: -179.6499987951282
				
				// rigth
				rotation x: -2.778563976287842 y: 1.5184382200241089 z: 1.9425514936447144
				rotation degreee x: -159.19998894838147 y: 87.00010145873853 z: 111.30000207267629
				
				// up
				rotation x: -3.104067802429199 y: 0 z: -3.135483980178833
				rotation degreee x: -177.8499844016414 y: 0 z: -179.6499987951282
				*/
				
			switch(e.currentTarget)
			{
				case _radBtnPerspectiveNormal:
						//_scene3D.setRotationScene(new Vector3D( -2.36, 0.52, 2.65));
						_scene3D.setPerspective(Scene3DAlter.PERSPECTIVE_CENTR);
						_perspectiveMessage.gotoAndStop(1);
					break;
				case _radBtnPerspectiveUp:
						//_scene3D.setRotationScene(new Vector3D(-3.1, 0.0, -3.14));
						_scene3D.setPerspective(Scene3DAlter.PERSPECTIVE_TOP);
						_perspectiveMessage.gotoAndStop(4);
					break;
				case _radBtnPerspectiveLeft:
						//_scene3D.setRotationScene(new Vector3D( -2.78, Math.PI * 0.5, 1.94));
						_scene3D.setPerspective(Scene3DAlter.PERSPECTIVE_LEFT);
						_perspectiveMessage.gotoAndStop(2);
					break;
				case _radBtnPerspectiveRight:
					//_scene3D.setRotationScene(new Vector3D( -1.59, 0.0,  -3.14));
					_scene3D.setPerspective(Scene3DAlter.PERSPECTIVE_RIGHT);
					_perspectiveMessage.gotoAndStop(3);
				break;
			}
			// listen when scene updated
			_scene3D.addEventListener(Scene3DEvent.SCENE_UPDATED, handleSceneUpdated);
		}
		
		private function handleSceneUpdated(e:Scene3DEvent):void 
		{
			_scene3D.removeEventListener(Scene3DEvent.SCENE_UPDATED, handleSceneUpdated);
			adjustScenePosition(null);
		}
		

		private function handleBtnRemoveFurnClick(e:MouseEvent):void 
		{
			_scene3D.removeSelected();
		}
		
		private function handleBtnAddFurnClick(e:MouseEvent):void 
		{
			/*if (_model.furnitureInf != null)
			{
				var furnForAdd:FurnitureModel = 
					_model.furnituresDict[_model.furnitureInf.furnitureID] as FurnitureModel;
				if (furnForAdd == null)
				{
					return;
				}
				_scene3D.addFurnitureWithPalette(furnForAdd,
												_model.paletteProvider.facadePalette,
												_model.paletteProvider.tabletopPalette,
												_model.paletteProvider.corpusPalette);
				return;
			}*/
			/*if (_model.furnitureForAdd != null)
			{
				_scene3D.addFurniture(_model.furnitureForAdd, 
									_model.currentFacadeTexture,
									_model.currentTabletopTexture);
				
			}else
			{
				trace("furniture null");
			}*/
			
			if (_model.furnitureForAdd != null)
			{
				//get sizes from scene3D
				// add sizes for current add
				var sizesNeeded:Vector.<String> = _scene3D.getSizesNeeded();
				sizesNeeded = sizesNeeded.concat(_model.furnitureForAdd.getSizesNeeded());
				_processType = PROCESS_ADD_FURNITURE;
				showMessageLoadingTextures();
				_model.paletteProvider.addEventListener(Event.COMPLETE, handlePaletteInited);
				_model.paletteProvider.prepareSizes(sizesNeeded);
				
				/*_scene3D.addFurnitureWithPalette(_model.furnitureForAdd,
												_model.paletteProvider.facadePalette,
												_model.paletteProvider.tabletopPalette,
												_model.paletteProvider.corpusPalette);*/
						
			}else
			{
				log("Add furniture null");
			}
		}
		
		private function showMessageLoadingTextures():void 
		{
			var pauseForShow:int = 15;
			if (_messageLoading == null)
			{
				_messageLoading = new MessageLoading(pauseForShow);
				
			}else if (_messageLoading.parent != null)
			{
				_messageLoading.parent.removeChild(_messageLoading);
			}
			
			_messageLoading.pauseBeforeShow = pauseForShow;
			_messageLoading.x = (AppSettings.APP_WIDTH - _messageLoading.windowWidth) * 0.5;
			_messageLoading.y = (AppSettings.APP_HEIGHT - _messageLoading.windowHeigth) * 0.5;
			addChild(_messageLoading);
			_messageLoading.show(pauseForShow);
		}
		
		private function hideMessageLoadingTextures():void
		{
			if (_messageLoading != null)
			{
				_messageLoading.hide();
			}
		}
		
		private function handlePaletteInited(e:Event):void 
		{
			log("Palette complete. Current process: " + _processType);
			switch(_processType)
			{
				case PROCESS_ADD_FURNITURE:
					log("_model.furnitureForAdd.itemType: " + _model.furnitureForAdd.itemType);
					_scene3D.addFurnitureWithPalette(_model.furnitureForAdd,
												_model.paletteProvider.facadePalette,
												_model.paletteProvider.tabletopPalette,
												_model.paletteProvider.corpusPalette,
												_model.paletteProvider.techPalette);
					/*if (_model.furnitureForAdd.itemType == FurnitureModel.ITEM_FURNITURE)
					{
						_scene3D.addFurnitureWithPalette(_model.furnitureForAdd,
												_model.paletteProvider.facadePalette,
												_model.paletteProvider.tabletopPalette,
												_model.paletteProvider.corpusPalette);
					}else
					{
						_scene3D.addFurnitureWithPalette(_model.furnitureForAdd,
														_model.paletteProvider.techPalette,
														null,
														null);
					}*/
					break;
				case PROCESS_UPDATE_FACADE:
					_scene3D.setFacadePalette(_model.paletteProvider.facadePalette, 
												_model.paletteProvider.techPalette);
					break;
				case PROCESS_UPDATE_TABLETOP:
					_scene3D.setTabletopPalette(_model.paletteProvider.tabletopPalette);
					break;
				case PROCESS_UPDATE_CORPUS:
					_scene3D.setCorpusPalette(_model.paletteProvider.corpusPalette);
					break;
			}
			
			_processType = PROCESS_NONE;
			hideMessageLoadingTextures();
		}
		
		private function handleBtnModulChooser(e:Event):void
		{
			switch(e.currentTarget)
			{
				case _roomSizeBtn:
						showRightModule(new ModuleRoomSize(_model));
					break;
				case _bottomFurnitureBtn:
						showRightModule(new ModuleChoseFurniture(_model, _model.bottomFurnitures));
					break;
				case _topFurnitureBtn:
						showRightModule(new ModuleChoseFurniture(_model, _model.topFurnitures));
					break;
				case _techFurnitureBtn:
						showRightModule(new ModuleChoseFurniture(_model, _model.techFurnitures));
					break;
			}
			
			updateRightBar();
		}
		
		private function updateRightBar():void 
		{
			//clear panel
			while (_activePanelHolder.numChildren > 0)
			{
				_activePanelHolder.removeChildAt(0);
			}
			
			var panel:DisplayObject = null;
			if (_roomSizeBtn.selected)
			{
				panel = _activePanelHolder.addChild(new PanelRoomSize());
				_btnAddFurniture.visible = false;
				_btnRemoveFurniture.visible = false;
			}else if (_bottomFurnitureBtn.selected)
			{
				panel = _activePanelHolder.addChild(new PanelBottomFurnitures());
				_btnAddFurniture.visible = true;
				_btnRemoveFurniture.visible = true;
			}
			else if (_topFurnitureBtn.selected)
			{
				panel = _activePanelHolder.addChild(new PanelTopFurnitures());
				_btnAddFurniture.visible = true;
				_btnRemoveFurniture.visible = true;
			}else if (_techFurnitureBtn.selected)
			{
				panel = _activePanelHolder.addChild(new PanelTech());
				_btnAddFurniture.visible = true;
				_btnRemoveFurniture.visible = true;
			}
			
			if (panel != null)
			{
				panel.y = _techFurnitureBtn.y + _techFurnitureBtn.height + 2;
			}
		}
		
		private function showRightModule(module:DisplayObject):void
		{
			if (_currentRightModule != null)
			{
				_currentRightModule.parent.removeChild(_currentRightModule);
				_currentRightModule = null;
			}
			if (module != null)
			{
				_currentRightModule = module;
				_moduleHolder.addChild(_currentRightModule);
			}
			
		}
		
		private function showBottomModule(module:DisplayObject):void
		{
			if (_currentBottomModule != null)
			{
				_currentBottomModule.parent.removeChild(_currentBottomModule);
			}
			_currentBottomModule = module;
			_bottomBar.addChild(_currentBottomModule);
			_currentBottomModule.y = 30;
		}
		
		private function createBottomBar():void 
		{
			_bottomBar = new Sprite();
			_bottomBar.x = 0;
			_bottomBar.y = StyleFactory.BOTTOM_MODULE_Y;
			addChild(_bottomBar);
			
			/*var btnBox:HBox = new HBox(_bottomBar, 0, 0);
			btnBox.spacing = 0;
			_btnFacadeChoose = new RadioButton();
			StyleFactory.setRadioButtonStyle(_btnFacadeChoose, StyleFactory.STYLE_RB_BOTTOM_MAIN);
			_btnFacadeChoose.label = "Выбрать фасад";
			btnBox.addChild(_btnFacadeChoose);
			//_btnFacadeChoose.addEventListener(MouseEvent.CLICK, facadeChooseClick);
			
			_btnTabletopChoose = new RadioButton();
			StyleFactory.setRadioButtonStyle(_btnTabletopChoose, StyleFactory.STYLE_RB_BOTTOM_MAIN);
			_btnTabletopChoose.label = "Выбрать столешницу";
			btnBox.addChild(_btnTabletopChoose);
			//_btnTabletopChoose.addEventListener(MouseEvent.CLICK, tabletopChooseClick);*/
			_moduleBottom = new ModuleBottom(_model);
			_moduleBottom.moduleWidth = StyleFactory.BOTTOM_MODULE_WIDTH;
			_moduleBottom.moduleHeight = StyleFactory.BOTTOM_MODULE_HEIGHT;
			_bottomBar.addChild(_moduleBottom);
			
			_moduleBottom.addEventListener(ModuleBottomEvent.TEXTURE_SELECTED, handleTextureSelected);
			
			var serviceBtnHolder:Sprite = new Sprite();
			var serviceBg:DisplayObject = new ServiceBg();
			serviceBg.x = 402;
			_bottomBar.addChild(serviceBg);
			
			var hBox:HBox = new HBox();
			hBox.spacing = 5;
			hBox.x = 412; // button with x2
			hBox.y = 3; 
			_bottomBar.addChild(hBox);
			
			_btnCalculate = new BaseButton();
			StyleFactory.setButtonStyle(_btnCalculate, StyleFactory.STYLE_BUTTON_CALC);
			hBox.addChild(_btnCalculate);
			
			_btnPrint = new BaseButton();
			StyleFactory.setButtonStyle(_btnPrint, StyleFactory.STYLE_BUTTON_PRINT);
			_btnPrint.addEventListener(MouseEvent.CLICK, handlePrintClick);
			hBox.addChild(_btnPrint);
			
			_btnFavorite = new BaseButton();
			_btnFavorite.addEventListener(MouseEvent.CLICK, handleFavoriteClick);
			StyleFactory.setButtonStyle(_btnFavorite, StyleFactory.STYLE_BUTTON_FAVORITE);
			hBox.addChild(_btnFavorite);
			
			_btnTutor = new BaseButton();
			_btnTutor.addEventListener(MouseEvent.CLICK , handleTutorClick);
			StyleFactory.setButtonStyle(_btnTutor, StyleFactory.STYLE_BUTTON_TUTOR);
			hBox.addChild(_btnTutor);
			
			_btnGallery = new BaseButton();
			StyleFactory.setButtonStyle(_btnGallery, StyleFactory.STYLE_BUTTON_GALLERY);
			_btnGallery.addEventListener(MouseEvent.CLICK, handleGalleryClick);
			hBox.addChild(_btnGallery);
			
			
		}
		
		private function handleFavoriteClick(e:MouseEvent):void 
		{
			if (_model.addFavoritesFunc == null || _model.addFavoritesFunc.length == 0) {
				return;
			}
			
			try {
				ExternalInterface.call(_model.addFavoritesFunc);
			}catch (err:Error) {
				log("Error call external func: " + err.name + "; " + err.message);
			}
		}
		
		private function handleGalleryClick(e:MouseEvent):void 
		{
			navigateToURL(new URLRequest(_model.galleryURL));
		}
		
		private function handleTutorClick(e:MouseEvent):void 
		{
			if(_videoModule == null){
				_videoModule = new TutorModule(_model.tutorVideoUrl);
			}else if (_videoModule.parent != null) {
				_videoModule.parent.removeChild(_videoModule);
			}
			
			_videoModule.y = StyleFactory.HEADER_HEIGHT;
			addChild(_videoModule);
			
		}
		
		private function handleTextureSelected(e:ModuleBottomEvent):void 
		{
			if (_processType != PROCESS_NONE)
			{
				log("wrong current process type: " + _processType);
				return;
			}
			
			switch(e.groupeInfo.targetSurface)
			{
				case TextureInfoGroupe.TARGET_SIDE_TABLETOP:
						_processType = PROCESS_UPDATE_TABLETOP;
					break;
				case TextureInfoGroupe.TARGET_SIDE_FACADE:
						_processType = PROCESS_UPDATE_FACADE;
					break;
				case TextureInfoGroupe.TARGET_SIDE_CORPUS:
						_processType = PROCESS_UPDATE_CORPUS;
					break;
			}
			
			showMessageLoadingTextures();
			_model.paletteProvider.addEventListener(Event.COMPLETE, handlePaletteInited);
			_model.paletteProvider.setupPalette(e.groupeInfo, e.textureInfo);
			_model.paletteProvider.prepareSizes(_scene3D.getSizesNeeded());
			
			
		}
		
		private function handlePrintClick(e:MouseEvent):void 
		{
			/*var rect:Rectangle = _scene3D.scene3D.getBounds(_scene3D);
			var bmData:BitmapData = new BitmapData(rect.width, rect.height);
			var matr:Matrix = new Matrix();
			matr.tx = -rect.x + _scene3D.scene3D.x;
			matr.ty = -rect.y + _scene3D.scene3D.y;
			bmData.draw(_scene3D.scene3D, matr, null, null, null, true);
			var page:Sprite = new Sprite();
			page.graphics.beginBitmapFill(bmData, null, false, true);
			page.graphics.drawRect(0, 0, bmData.width, bmData.height);
			page.graphics.endFill();
			PrintPage.print(page);
			/*_testShape.addChild(page);
			addChild(page);
			var gr:Graphics = _scene3D.graphics;
			gr.clear();
			gr.lineStyle(1);
			gr.drawRect(rect.x, rect.y, rect.width, rect.height);
			log("rect x: " + rect.x + " y: " + rect.y + " w: " + rect.width + " h: " + rect.height);
			log(" bmData: " + bmData.width + " h: " +  bmData.height);*/
			
			var bmData:BitmapData = _scene3D.getFieldBitmapData();
			var page:Sprite = new Sprite();
			page.graphics.beginBitmapFill(bmData, null, false, true);
			page.graphics.drawRect(0, 0, bmData.width, bmData.height);
			page.graphics.endFill();
			PrintPage.print(page);
		}
		
		private function adjustScenePosition(e:Scene3DEvent):void
		{
			
			var boundRect:Rectangle;
			//var points:Vector.<Point>;
			var centrPoint:Point;
			centrPoint = _scene3D.getRoomCentr();
			
			switch(_scene3D.currentPerspective) {
				case Scene3DAlter.PERSPECTIVE_CENTR:
						boundRect = _scene3D.getBoundsRect(Scene3DAlter.ROOM);
						
					break;
				case Scene3DAlter.PERSPECTIVE_LEFT:
						boundRect = _scene3D.getBoundsRect(Scene3DAlter.RIGHT_WALL);
					break;
				case Scene3DAlter.PERSPECTIVE_RIGHT:
						boundRect = _scene3D.getBoundsRect(Scene3DAlter.LEFT_WALL);
					break;
				case Scene3DAlter.PERSPECTIVE_TOP:
						boundRect = _scene3D.getBoundsRect(Scene3DAlter.BOTTOM_WALL);
					break;
			}
			
			
			
			if (boundRect == null) {
				log("Bounds null: " + boundRect);
				return;
			}
			
			
			var targetX:Number = (_sceneWidth - boundRect.width) * 0.5;
			var targetY:Number = 0;
			
			if (_scene3D.currentPerspective == Scene3DAlter.PERSPECTIVE_CENTR) {
				centrPoint.x = boundRect.x + boundRect.width * 0.5;
			}
			
			if (_scene3D.currentPerspective ==  Scene3DAlter.PERSPECTIVE_CENTR && (boundRect.height> _sceneHeight)) {
				targetY = 0;
			}else {
				 targetY = (_sceneHeight - boundRect.height) * 0.5;
			}
			
			
			
			if ((targetX < 0) || (targetX > _sceneWidth)) {
				targetX = _sceneWidth * 0.5;
			}
			
			if ((targetY < 0) || (targetY > _sceneHeight)) {
				targetY = _sceneHeight * 0.5;
			}
			
			
			targetX += centrPoint.x - boundRect.x;
			targetY += centrPoint.y - boundRect.y;
			
			if ((targetX < 0) || (targetX > _sceneWidth)) {
				targetX = _sceneWidth * 0.5;
			}
			
			if ((targetY < 0) || (targetY > _sceneHeight)) {
				targetY = _sceneHeight * 0.5;
			}
			
			_scene3D.setRoomScreenPos(targetX, targetY);
			
			
		
			/*var gr:Graphics = _testShape.graphics;
			gr.clear();
			gr.lineStyle(2, 0xFF0000);
			gr.drawRect(targetX, targetY, boundRect.width, boundRect.height);
			gr.beginFill(0x0000FF, 1);
			gr.drawCircle(centrPoint.x, centrPoint.y, 8);
			gr.endFill();*/
			/*	var rect:Rectangle = _scene3D.getBounds(_scene3D.parent);
			//log("adjustScenePosition rect x: " + rect.x + 
			//	" y: " + rect.y + " w: " + rect.width + " h: " + rect.height);
			_scene3D.x -= rect.x - (SCENE3D_WIDTH - rect.width) * 0.5;
			_scene3D.y -= rect.y - (SCENE3D_HEIGHT - rect.height) * 0.5;
			//log("Scene x: " + _scene3D.x + " y: " + _scene3D.y);
			
			//var gr:Graphics = (_scene3D.parent as Sprite).graphics;
			/*var gr:Graphics = _testShape.graphics;
			gr.clear();
			gr.lineStyle(1);
			gr.drawRect(rect.x, rect.y, rect.width, rect.height);
			gr.beginFill(0xFF0000);
			gr.drawCircle(_scene3D.x, _scene3D.y, 5);
			gr.endFill();*/
		}
		
		
		private function tabletopChooseClick(e:MouseEvent):void 
		{
			showBottomModule(new ModuleTabletopChoose(_model));
		}
		
		private function facadeChooseClick(e:MouseEvent):void 
		{
			showBottomModule(new ModuleFacadeChoose(_model));
		}
		
		private function createTopBar():void 
		{
			var header:DisplayObject = new HeaderMovie();
			addChild(header);
		}
		
		
		
	}

}